<template>
  <view class="container">
    <tree 
      ref="treeRef"
      :data="treeData" 
      :showCheckbox="false" 
      @node-click="handleNodeClick"
      @check-change="handleCheckChange"
      :defaultExpandAll="true"
    />
    
    <!-- <button @click="getCheckedNodes">获取选中的节点</button> -->
  </view>
</template>

<script setup>
import { ref, onMounted, onUnmounted } from 'vue'
import tree from '@/packageA/components/tree/tree.vue'
import request from "@/utils/request.js";
import {
  useDictionaryStore,
  useUserStore
} from '@/store/index.js'
  // 字典仓库
const dictionaryStore = useDictionaryStore()
const treeRef = ref(null)

const treeData = ref([])

const handleNodeClick = (data) => {
  console.log('节点点击:', data)
  if(data.children) return
  let path = '';
  if (data.msgType === '1') {
    path = '/notice/list';
  } else {
    let operateTypeConfig = { path: '' };
    try {
      const operateTypeDictionary =
        dictionaryStore.get('decoration_order_operate_type').find((item) => item.value === data.operateType) || {};
      operateTypeConfig = JSON.parse(operateTypeDictionary.remark);
      console.log(operateTypeDictionary,'operateTypeDictionary');
    } catch {
    //   MessagePlugin.warning('解析操作配置失败，请联系管理员。');
      return;
    }
    path = operateTypeConfig.path;
  }
  if (!path) {
    // MessagePlugin.warning('未匹配到相对应页面，请联系管理员。');
    return;
  }
//   disposableParams.set('to-do-tree-jump-params', {
//     noticeIds: data.ids,
//     orderIds: data.orderIds,
//     operateType: data.operateType,
//     oaType: data.oaType,
//     clueIds: data.clueIds,
//     stageType: data.stageType,
//   });
const params = {
  noticeIds: data.ids,
  orderIds: data.orderIds,
  operateType: data.operateType,
  oaType: data.oaType,
  clueIds: data.clueIds,
  stageType: data.stageType
};

  	// 将对象转换为查询字符串
const queryString = Object.keys(params)
  .map(key => `${encodeURIComponent(key)}=${encodeURIComponent(params[key])}`)
  .join('&');

uni.navigateTo({
  url: `/packageA/pages${path}?${queryString}`
});
}

const handleCheckChange = (node) => {
  console.log('复选框变化:', node)
}

const getCheckedNodes = () => {
  const checkedNodes = treeRef.value.getCheckedNodes()
  console.log('选中的节点:', checkedNodes)
  uni.showToast({
    title: `选中了 ${checkedNodes.length} 个节点`,
    icon: 'none'
  })
}
// 处理删除空子节点
const handleDeleteEmptyChildren = (arr) => {
  const deleteIndexs = [];
  arr.forEach((item, index) => {
    if (item.children && Array.isArray(item.children) && item.children.length) {
      handleDeleteEmptyChildren(item.children);
    }
    if (!item.children?.length && !item.orderIds && !item.clueIds) {
      deleteIndexs.unshift(index);
    }
  });
  deleteIndexs.forEach((index) => arr.splice(index, 1));
  return arr;
};
// 处理获取数据树
const handleGetDataTree = () => {
//   loading.value = true;
  request
    .get('/system/message-notify/get-message-tree')
    .then((data) => {
      treeData.value = handleDeleteEmptyChildren(data);
    })
    .finally(() => {
    //   loading.value = false;
    });
};
// 定时器引用
const refreshTimer = ref(null);
// 启动定时刷新
const startAutoRefresh = () => {
  // 先清除已有定时器
  if (refreshTimer.value) {
    clearInterval(refreshTimer.value);
  }
  // 设置新的定时器（每分钟刷新一次）
  refreshTimer.value = setInterval(() => {
    handleRefresh();
  }, 60 * 1000); // 60秒 = 60000毫秒
};
// 处理刷新
const handleRefresh = () => {
  
  request
    .get('/system/message-notify/get-message-tree')
    .then((data) => {
      const newData = handleDeleteEmptyChildren(data);
      
      treeData.value = newData
    })
    .finally(() => {
      loading.value = false;   
    });
};
onMounted(() => {
  handleGetDataTree(); // 初始加载
  startAutoRefresh();  // 启动定时刷新
});
// 组件卸载时
onUnmounted(() => {
  // 清除定时器
  if (refreshTimer.value) {
    clearInterval(refreshTimer.value);
  }
});
</script>